package com.dng.book.controller;

import com.dng.book.common.Result;
import com.dng.book.dto.LoginRequest;
import com.dng.book.service.TokenService;
import com.dng.book.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import com.dng.book.dto.UploadAvatarRequest;
import cn.hutool.core.util.StrUtil;

/**
 * 用户控制器
 *
 * @author dng
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Tag(name = "用户管理", description = "用户相关接口")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;

    @Operation(summary = "用户登录", description = "用户登录接口")
    @PostMapping("/login")
    public Result<Map<String, String>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            String token = userService.login(loginRequest);
            Map<String, String> result = new HashMap<>();
            result.put("token", token);
            result.put("username", loginRequest.getUsername());
            return Result.success("登录成功", result);
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "用户登出", description = "用户登出接口")
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        if (token != null) {
            tokenService.removeToken(token);
            log.info("用户登出成功");
        }
        return Result.success("登出成功");
    }
    
    @Operation(summary = "上传头像", description = "上传用户头像")
    @PostMapping("/uploadAvatar")
    public Result<String> uploadAvatar(@RequestBody UploadAvatarRequest request) {
        try {
            String username = request.getUsername();
            String avatarData = request.getAvatarData();
            String fileType = request.getFileType();
            
            if (StrUtil.isBlank(username) || StrUtil.isBlank(avatarData)) {
                return Result.error("参数不能为空");
            }
            
            // 生成头像URL（这里使用Base64数据URL）
            String avatarUrl = "data:" + fileType + ";base64," + avatarData;
            
            boolean success = userService.uploadAvatar(username, avatarUrl);
            if (success) {
                log.info("头像上传成功 - 用户名: {}", username);
                return Result.success("头像上传成功", avatarUrl);
            } else {
                log.error("头像上传失败 - 用户名: {}", username);
                return Result.error("头像上传失败");
            }
        } catch (Exception e) {
            log.error("头像上传异常", e);
            return Result.error("系统异常，请稍后重试");
        }
    }
    
    @Operation(summary = "获取头像", description = "获取用户头像")
    @GetMapping("/getAvatar")
    public Result<String> getAvatar(@RequestParam String username) {
        try {
            if (StrUtil.isBlank(username)) {
                return Result.error("用户名不能为空");
            }
            
            String avatarUrl = userService.getAvatar(username);
            if (avatarUrl != null) {
                return Result.success("获取头像成功", avatarUrl);
            } else {
                return Result.error("头像不存在");
            }
        } catch (Exception e) {
            log.error("获取头像异常", e);
            return Result.error("系统异常，请稍后重试");
        }
    }

    /**
     * 从请求中获取Token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        // 优先从请求头中获取
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        
        // 从请求参数中获取
        return request.getParameter("token");
    }
} 